<template>
  <a-spin :spinning="loading">
    <Form ref="formRef" />
    <div :class="[`${prefixCls}`]">
      <a-button preIcon="ant-design:sync-outlined" @click="onReset(model)">重置</a-button>
      <a-button type="primary" preIcon="ant-design:save-filled" @click="onSubmit">保存</a-button>
    </div>
  </a-spin>
</template>

<script lang="ts" setup>
  import { watch, computed, ref, unref, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { saveOrUpdateDepart } from '../api';
  import { useBasicFormSchema, orgCategoryOptions } from '../data';
  import { useDesign } from '/@/hooks/web/useDesign';
  import Form, { Exposed }  from './Form.vue'
  import { mode } from 'crypto-js';

  const { prefixCls } = useDesign('j-depart-form-content');

  const emit = defineEmits(['success']);
  const props = defineProps({
    data: { type: Object, default: () => ({}) },
    rootTreeData: { type: Array, default: () => [] },
  });
  const loading = ref<boolean>(false);
  // 当前是否是更新模式
  const isUpdate = ref<boolean>(true);
  // 当前的弹窗数据
  const model = ref<object>({});

  //注册表单
  // const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  //   schemas: useBasicFormSchema().basicFormSchema,
  //   showActionButtonGroup: false,
  // });

  const categoryOptions = computed(() => {
    if (!!props?.data?.parentId) {
      return orgCategoryOptions.child;
    } else {
      return orgCategoryOptions.root;
    }
  });
  

  onMounted(() => {
    // 禁用字段
    // updateSchema([
    //   { field: 'parentId', componentProps: { disabled: true } },
    //   { field: 'orgCode', componentProps: { disabled: true } },
    // ]);
    // data 变化，重填表单
    watch(
      () => props.data,
      async () => {
        let record = unref(props.data);
        if (typeof record !== 'object') {
          record = {};
        }
        model.value = record;
        onReset({...record})
        // await resetFields();
        // await setFieldsValue({ ...record });
      },
      { deep: true, immediate: true }
    );
    // 更新 父部门 选项
    watch(
      () => props.rootTreeData,
      async () => {
        // updateSchema([
        //   {
        //     field: 'parentId',
        //     componentProps: { treeData: props.rootTreeData },
        //   },
        // ]);
        if (formRef.value) {
          await formRef.value.updateTreeData(props.rootTreeData)
        }
      },
      { deep: true, immediate: true }
    );
    // 监听并更改 orgCategory options
    watch(
      categoryOptions,
      async () => {
        // updateSchema([
        //   {
        //     field: 'orgCategory',
        //     componentProps: { options: categoryOptions.value },
        //   },
        // ]);
        if (formRef.value) {
          await formRef.value.updateCategoryOptions(categoryOptions.value)
        }
      },
      { immediate: true }
    );
  });

  const formRef = ref<Exposed | null>(null)

  // 重置表单
  async function onReset(data) {
    if (formRef.value) {
      await formRef.value.resetForm(data)
    }
    // await resetFields();
    // await setFieldsValue({ ...model.value });
  }

  // 提交事件
  async function onSubmit() {
    try {
      loading.value = true;
      if (formRef.value) {
        let values = await formRef.value.onSubmit()
        // console.log('子组件返回:', values)
        // let values = await validate();
        values = Object.assign({}, model.value, values);
        //提交表单
        // console.log(values, isUpdate.value);
        await saveOrUpdateDepart(values, isUpdate.value);
        //刷新列表
        emit('success');
        Object.assign(model.value, values);
      }
    } finally {
      loading.value = false;
    }
  }
</script>
<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-j-depart-form-content';
  .@{prefix-cls} {
    background: @component-background;
    border-top: 1px solid @border-color-base;
    padding-top: 15px;
    display: flex;
    justify-content: flex-end;
    > .ant-btn {
      margin-left: 10px;
    }
  }
</style>
